# -*- coding: utf-8 -*-
# This code is opensource under WTFPL.
# Author: squaresum
import re
from tqdm import tqdm
import downloader
import content_parser


class Supervisor:
    def __init__(self):
        self.strategies = [
            ('IIIF', lambda url: re.match(r'.+manifest(\.json)?', url), self.getIIIF),
            ('tokyo', lambda url: re.match(
                r'http(s)+:\/\/clioimg\.hi\.u-tokyo\.ac\.jp\/viewer\/view\/.+', url), self.getTokyo1),
            ('tokyo', lambda url: re.match(
                r'http(s)+:\/\/clioimg\.hi\.u-tokyo\.ac\.jp\/viewer\/list\/.+', url), self.getTokyo2),
            ('HathiTrust', lambda url: re.match(
                r'http(s)+:\/\/babel\.hathitrust\.org\/cgi\/pt.+', url), self.getHathiTrust)
        ]

    def start(self, url):
        """
        根据URL的格式选择正确的方法进行爬取。
        """
        for strategy in self.strategies:
            if strategy[1](url):
                strategy[2](url)
                return

        print('没有匹配到任何规则，请检查传入的URL。')

    def getIIIF(self, url):
        """
        从IIIF Menifest JSON批量下载文件。
        """
        jsonStr = downloader.getContent(url)
        picList = content_parser.IIIFParser(jsonStr)
        print('IIIF JSON items: {}'.format(len(picList)))
        self.downloadPicList(picList)

    def getTokyo1(self, url):
        """
        第一种从东京大学史料编纂所批量下载文件的方法。
        从图片查看页进行下载。
        """
        htmlStr = downloader.getContent(url)
        isOriginal = url.split('/')[-4] != '8500'
        picList = content_parser.TokyoViewParser(htmlStr, url, isOriginal)
        print('Tokyo items: {}'.format(len(picList)))
        self.downloadPicList(picList)

    def getTokyo2(self, url):
        """
        第二种从东京大学史料编纂所批量下载文件的方法。
        从图片列表页进行下载。
        """
        htmlStr = downloader.getContent(url)
        # 如果URL倒数第四部分不为8500则该页面展示的是未经翻刻的原始史料
        isOriginal = url.split('/')[-4] != '8500'
        picList = content_parser.TokyoListParser(htmlStr, isOriginal)
        print('Tokyo items: {}'.format(len(picList)))
        self.downloadPicList(picList)

    def getHathiTrust(self, url):
        id = re.findall(r'id=[^&]+', url)[0].replace('id=', '')
        htmlStr = downloader.getContent(url)
        picList = content_parser.HathiTrustListParser(htmlStr, id)
        print('HathiTrust items: {}'.format(len(picList)))
        self.downloadPicList(picList, list('{}.jpg'.format(num) for num in range(1, len(picList)+1)))

    def downloadPicList(self, picList, nameList=None):
        """
        对图片进行批量下载并显示进度条。
        """
        if nameList:
            for picUrl, filename in tqdm(zip(picList, nameList), desc="Downloading..."):
                downloader.getPicture(picUrl, filename)
        else:
            for picUrl in tqdm(picList, desc="Downloading..."):
                downloader.getPicture(picUrl)